from datetime import datetime
from app.models.db_setup import db


class User(db.Model):
    __tablename__ = "User"

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    openid = db.Column(db.String(255), unique=True, nullable=False)
    username = db.Column(db.String(255), nullable=False)
    role = db.Column(
        db.Enum("admin", "employee", "customer", "none", name="user_role"),
        nullable=False,
        default="none",
    )
    created_at = db.Column(db.DateTime, server_default=db.func.now())

    def __init__(self, openid, username, role="none"):
        self.openid = openid
        self.username = username
        self.role = role

    def is_admin(self):
        return self.role == "admin"

    def is_employee(self):
        return self.role == "employee"

    def is_staff(self):
        return self.role == "employee" or self.role == "admin"

    def is_customer(self):
        return self.role == "customer"

    def to_dict(self):
        return {
            "id": self.id,
            "openid": self.openid,
            "username": self.username,
            "role": self.role,
            "created_at": self.created_at.isoformat() if self.created_at else None,
        }
